package cn.net.isir.service;

import cn.net.isir.common.TokenManager;
import cn.net.isir.core.BasicService;
import cn.net.isir.core.SetBasicDao;
import cn.net.isir.dao.MessageDao;
import cn.net.isir.dao.MessageReadStatusDao;
import cn.net.isir.entity.Message;
import cn.net.isir.entity.MessageReadStatus;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MessageService extends BasicService<Message> {
    @SetBasicDao
    @Resource
    private MessageDao messageDao;
    @Resource
    private MessageReadStatusDao messageReadStatusDao;


    @Override
    public PageInfo<Message> selectPageList(Message parameter, Integer pageNo, Integer pageSize) {
        PageInfo<Message> pageInfo = messageDao.selectPageList(parameter, pageNo, pageSize);
        return pageInfo;
    }

    @Override
    public int insert(Message parameter) {
        parameter.setCreater(TokenManager.getTokenId());
        parameter.setCreateUser(TokenManager.getTokenId());
        // 如果发布了,设置发布时间
        if (parameter.getIsPublished() == 1) {
            parameter.setPublishTime(new Date());
        }
        return super.insert(parameter);
    }

    /**
     * 查询本机构收到的消息
     *
     * @param pOrgOR 机构列表,用|分隔(便于消息中的多个机构对本机构的多个父级机构的时候,正则匹配)
     * @return 列表
     */
    public PageInfo<Message> getMyOrgMessage(String pOrgOR, String search, Integer pageNo, Integer pageSize, String userId) {
        Map<String, String> map = new HashMap<>();
        map.put("pOrgOR", pOrgOR);
        map.put("search", search);
        PageInfo<Message> info = messageDao.selectPageList(map, "getMyOrgMessage", pageNo, pageSize);

        for (Message message1 : info.getList()) {
            message1.setType("notification");
            MessageReadStatus mrs = new MessageReadStatus();
            mrs.setMsgId(message1.getId());
            mrs.setUserId(userId);
            mrs = messageReadStatusDao.selectOne(mrs);
            message1.setRead(false);
            if (mrs != null) {
                message1.setRead(true);
            }
        }
        return info;
    }

    /**
     * 根据组织机构ID查询包含此ID的通知列表
     * @param orgId 组织机构id
     * @return 通知列表
     */
    public List<Message> findMsgListByOrgId(String orgId){
        return messageDao.findMsgListByOrgId(orgId);
    }

}
